/**
 * Created by user on 2015/9/18.
 */


var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var banner = mongoose.model('banner');
var User = mongoose.model('user');
var Community = mongoose.model('community');
var toolUtil = require('../../../common/utils/toolUtil');

exports.bannerListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    var sortType = paged ? {endDate:-1} : {};

    if (option.name) option.name = new RegExp(option.name);
    logger.debug(option);
    async.series([

        function (callbackInner) {
            banner.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            banner.find(option).sort({beginDate:-1}).skip(index).limit(size)
                .populate('province', '_id name')
                .populate('city', '_id name')
                .populate('county', '_id name')
                .populate('community', '_id communityName')
                .exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {
                        callbackInner(null, results);
                    }
                });

        }], callback);

};

exports.bannerAddService = function(req ,callback) {

    var body = req.body;
    logger.debug(body);
    var data = {
        //contentId: body.contentId
        type : body.type
        ,openType: body.openType
        ,name : body.name
        ,url: body.url
        ,level : body.level
        ,beginDate : body.beginDate
        ,endDate : body.endDate
    };

    var contentId;

    if(data.url){
        data.url = data.url.replace('&source=banner','');
        data.url = data.url.replace('?source=banner','');

        if(data.url.indexOf('?')>0){
            data.url += '&source=banner';
        }else{
            data.url += '?source=banner';
        };

        contentId = toolUtil.getQueryString(data.url,'topicId');
    };

    if (body.provinceId)  data.province = body.provinceId;
    if (body.cityId)  data.city = body.cityId;
    if (body.countyId)  data.county = body.countyId;
    if (body.imageURL) data.imageURL = body.imageURL;

    logger.debug(data);

    if(contentId){

        redisClient.HGET('topicIdPool',contentId, function (err, res) {
            if(res){
                data.contentId = res;
            }else{
                data.contentId = contentId;
            };

            if (body.community && body.community.length > 0) {

                async.each(body.community, function (community, callbackInner) {
                    data.community = community;
                    var temp = new banner(data);
                    temp.save(callbackInner);
                }, function (err) {
                    callback(err, null);
                });

            } else {
                var temp = new banner(data);
                temp.save(callback);
            };

        });

    }else {
        if (body.community && body.community.length > 0) {

            async.each(body.community, function (community, callbackInner) {
                data.community = community;
                var temp = new banner(data);
                temp.save(callbackInner);
            }, function (err) {
                callback(err, null);
            });

        } else {
            var temp = new banner(data);
            temp.save(callback);
        };
    }
};

exports.bannerDeleteService = function (req, callback) {

    var ids = req.body.bannerID;

    var queryUserIn = {};
    queryUserIn["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        queryUserIn["$in"].push(ids[i]);
    }
    logger.debug(queryUserIn);
    banner.remove({_id :queryUserIn}, callback);
};

exports.bannerEditService = function(req ,callback) {

    var body = req.body;

    //if (!(body.provinceId && body.cityId && body.countyId && body.city && body.communityName && body.communityAddress)) {
    //    return callback("缺少小区基础数据",null);
    //}
    //logger.debug(body);
    if(body.banner.url){
        body.banner.url = body.banner.url.replace('&source=banner','');
        body.banner.url = body.banner.url.replace('?source=banner','');

        if(body.banner.url.indexOf('?')>0){
            body.banner.url += '&source=banner';
        }else{
            body.banner.url += '?source=banner';
        };

        var contentId = toolUtil.getQueryString(body.banner.url,'topicId');

        if(contentId){
            redisClient.HGET('topicIdPool',contentId, function (err, res) {
                if(res){
                    body.banner.contentId = res;
                    logger.debug(body);
                    banner.update({_id: body.bannerID}, body.banner, callback);
                }
                else{
                    body.banner.contentId = contentId;
                    logger.debug(body);
                    banner.update({_id: body.bannerID}, body.banner, callback);
                };
            });

        }else{
            logger.debug(body);
            banner.update({_id: body.bannerID}, body.banner, callback);
        }

    }else{
        logger.debug(body);
        banner.update({_id: body.bannerID}, body.banner, callback);
    }
};

exports.bannerPushService = function (req, callback){

    var input = req.body;

    if(input.url){
        input.url = input.url.replace('&source=banner','');
        input.url = input.url.replace('?source=banner','');
        //if(input.url.indexOf('?')>0){
        //    input.url += '&source=notify';
        //}else{
        //    input.url += '?source=notify';
        //};
    };

    var option = input.pushCommunity;
    logger.debug(option);
    logger.debug(input);

    redisClient.HGET('topicIdPool',input.contentId, function (err, res) {
        logger.debug(res);
        if(res){
            input.contentId = res;
        };

        if(Number(input.level) ==2 || Number(input.level) ==1 || Number(input.level) ==0){
        //var openType = 1;
        //if(Number(input.openType) == 4) openType = 2;
        //按标签推送
        //logger.debug(input.tags);

            var tag = '';

            switch (Number(input.level)){
                case 0:
                    tag = 'all'
                    break;
                case 1:
                    tag = input.pushCommunity.provinceId;
                    break;
                case 2:
                    tag = input.pushCommunity.cityId;
                    break;
            };


            var pushData = {
                //tags: input.tags,
                //content: content,
                type: 1,
                flag: 2,
                openType: input.openType,
                contentId: input.contentId,
                //createdBy: input.createdBy,
                ds: input.desc,
                url: input.url,
                ip: req.headers['X-Real-IP'],
                tag: tag,
                type: 'operate',
                msgType: 'banner_push'
            };
            logger.debug(pushData);
            toolUtil.putMessageTagPushMQ(pushData);

        callback(null, {});

    }else {
            Community.find(option, function (err, result) {
                //遍历小区
                async.eachSeries(result, function (community, callbackInner) {
                    logger.debug(community.communityName);
                    User.find({community: community}).exec(function (err, result) {

                        if (result) {
                            var userList = [];
                            if (result) {
                                for (user in result) {
                                    userList.push(result[user]._id);
                                }
                                ;
                            }
                            ;


                            var content = {
                                type: 1,
                                flag: 2,
                                openType: input.openType,
                                contentId: input.contentId,
                                //createdBy: input.createdBy,
                                desc: input.desc,
                                url: input.url
                            };
                            var pushData = {
                                uList: userList,
                                content: content,
                                ip: req.headers['X-Real-IP'],
                                tag: input.tag,
                                type: 'operate',
                                msgType: 2
                            };
                            toolUtil.putMessageGetuiPushMQ(pushData);
                        }
                        ;
                        callbackInner(err, result);
                    });


                }, function (err) {
                    callback(err, null);
                });


            });

        };

    });
};


//var pushData = {
//    tags: [],
//    content: content,
//    ip: req.headers['X-Real-IP'],
//    tag: input.tag,
//    type: 'operate',
//    msgType:2
//};